//
//  RWShoppingCart2ViewController.m
//  RedWine
//
//  Created by Liufangfang on 2016/12/29.
//  Copyright © 2016年 HuiBangKe. All rights reserved.
//

#import "RWShoppingCart2ViewController.h"
#import "ShopCartGoodViewCell.h"
#import "bottomPriceView.h"
#import "RWBalanceViewController.h"

@interface RWShoppingCart2ViewController ()

@end

@interface RWShoppingCart2ViewController () <UITableViewDataSource, UITableViewDelegate, ShopCartGoodViewCellDelegate, bottomPriceViewDelegate, UITextFieldDelegate>

@property (strong, nonatomic) UITableView *tableView;
/**购物车的所有内容*/
@property (nonatomic, strong) NSMutableDictionary *shopCartDic;
@property (nonatomic, strong) NSMutableArray *shopNameArray;
/**选着的商品*/
@property (nonatomic, strong) NSMutableArray *selectedArray;
/**选中的店铺*/
@property (nonatomic, strong) NSMutableArray *selectedStoreArr;
/**购物车每件商品的模型数组*/
@property (nonatomic, strong) NSMutableArray *modelArr;
/**总价格*/
@property (nonatomic, assign) double allSum;

@property (weak, nonatomic) UIBarButtonItem *barBtn;

@property (nonatomic, strong) bottomPriceView *bottonView;
@property (weak, nonatomic) UITextField *countText;
@property (nonatomic, assign) NSInteger currentCount;
@property (nonatomic, strong) ShopCartModel *currentModel;
@property (nonatomic, strong) ShopCartGoodViewCell *currentCell;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation RWShoppingCart2ViewController

#pragma mark - View LifeCycle

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //[self getShopCartData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigation];
    [self mainView];
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];

    if ([FTYUser sharedUser].userID.length > 0) {
        
        [self getShopCartData];
    } else {
        
        [FTYLoginManager reLoginFromViewController:self];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Load Datas

//请求数据 得到有无选着的店铺设置物品的select
- (void)getShopCartData{
    
    //先清空选中的
    [self.selectedArray removeAllObjects];
    [self.selectedStoreArr removeAllObjects];
    [self.modelArr removeAllObjects];
    self.bottonView.isSelectBtn = NO;
    
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=cartlist&member_id=%@&token=%@", user.userID, user.userToken] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"购物车====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                NSMutableArray *array = [NSMutableArray array];
                [array addObjectsFromArray:baseModel.info];
                
                for (NSDictionary *dic in array) {
                    ShopCartModel *model = [ShopCartModel mj_objectWithKeyValues:dic];
                    if (![self.shopNameArray containsObject:@(model.cart_id)]) {
                        [self.shopNameArray addObject:@(model.cart_id)];
                    }
                }
                //字典数组 ==> 模型数组
                _modelArr = [ShopCartModel mj_objectArrayWithKeyValuesArray:array];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TabbarShopCartNumberShowNotification" object:@{@"number": @(_modelArr.count)}];
                
                for (NSNumber *number in self.shopNameArray) {
                    NSMutableArray *array = [NSMutableArray new];
                    for (ShopCartModel *model in _modelArr) {
                        if (model.cart_id == [number integerValue]) {
                            [array addObject:model];
                        }
                    }
                    [self.shopCartDic setObject:array forKey:number];
                }
                NSLog(@"购物车列表=====%@", self.shopNameArray);
                
                //结算
                self.bottonView.hidden = NO;
                self.barBtn.enabled = YES;
                self.tableView.height = FTY_SCREEN_HEIGHT - kFit(50);
                [self.tableView reloadData];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            DLog(@"购物车获取信息失败：%@", result);
        }
    }];
}

- (NSMutableArray *)modelArr{
    if (!_modelArr) {
        _modelArr = [NSMutableArray new];
    }
    return _modelArr;
}
//一个key对应该商店的所有商品
- (NSMutableDictionary *)shopCartDic{
    if (!_shopCartDic) {
        _shopCartDic = [NSMutableDictionary new];
    }
    return _shopCartDic;
}
- (NSMutableArray *)shopNameArray{
    if (!_shopNameArray) {
        _shopNameArray = [NSMutableArray new];
    }
    return _shopNameArray;
}
/**被选中的商品*/
- (NSMutableArray *)selectedArray{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray new];
    }
    return _selectedArray;
}
/**被选中的店铺*/
- (NSMutableArray *)selectedStoreArr{
    if (!_selectedStoreArr) {
        _selectedStoreArr = [NSMutableArray new];
    }
    return _selectedStoreArr;
}

#pragma mark - Config UI Methods

- (void)setNavigation{

    self.title = @"购物车";
    UIBarButtonItem *bar = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editClick:)];
    self.navigationItem.rightBarButtonItem = bar;
    self.barBtn = bar;
}

- (void)mainView{
    
    //解决UIScrollView显示内边距
//    self.automaticallyAdjustsScrollViewInsets = YES;
    
    //UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT - FTY_TABBAR_HEIGHT - kFit(50) - 85*FTY_HEIGHT_BASE) style:UITableViewStylePlain];
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT - FTY_TABBAR_HEIGHT - 44 - FTY_STATUS_HEIGHT-FTY_NAVIGATION_HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:tableView];
//    UIEdgeInsets insets = UIEdgeInsetsMake(-35, 0, 0, 0);
//    tableView.contentInset = insets;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView = tableView;
    
    self.bottonView = [[bottomPriceView alloc] initWithFrame:CGRectMake(0, 485*FTY_HEIGHT_BASE, FTY_SCREEN_WIDTH, kFit(50))];
    self.bottonView.frame = CGRectMake(0, FTY_SCREEN_HEIGHT-64-FTY_TABBAR_HEIGHT-44, FTY_SCREEN_WIDTH, 44);
    NSLog(@"frame:%@",NSStringFromCGRect(self.bottonView.frame));
    [self.view addSubview:self.bottonView];
    self.bottonView.backgroundColor = [UIColor whiteColor];
    self.bottonView.delegate = self;
    self.allSum = 0;
}

//编辑
- (void)editClick:(UIBarButtonItem *)sender{
    
    if ([sender.title isEqualToString:@"编辑"]) {
        
        self.bottonView.changeStr = @"删除";
        [sender setTitle:@"完成"];
    }else{
        
        self.bottonView.changeStr = @"结算";
//        self.bottonView.selectedBtn.hidden = YES;
        [sender setTitle:@"编辑"];
    }
}

#pragma mark - tableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _modelArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return kFit(1);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return kFit(130);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

        static NSString *ID = @"shopCartGoodCell";
        ShopCartGoodViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            
            cell = [[ShopCartGoodViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            cell.countTextField.delegate = self;
        }
        cell.model = _modelArr[indexPath.row];
        return cell;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    //设置删除按钮
    if (indexPath.row != 0) {
        
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
            //删除操作 给后台发送删除请求
            //删除 缓存数据
            //1.取出对应的商店的所有商品数组
            NSMutableArray *array = [self.shopCartDic objectForKey:self.shopNameArray[indexPath.section]];
            //2.0删除对应商品
            ShopCartModel *model = array[indexPath.row - 1];
            [array removeObjectAtIndex:(indexPath.row - 1)];
            //2.1删除已选中商品
            if ([self.selectedArray containsObject:model]) {
                [self.selectedArray removeObject:model];
            }
            if (array.count == 0) {
                //删除已选中商店
                if ([self.selectedStoreArr containsObject:@(model.cart_id)]) {
                    [self.selectedStoreArr removeObject:@(model.cart_id)];
                }
                [self.shopCartDic removeObjectForKey:self.shopNameArray[indexPath.section]];
                [self.shopNameArray removeObjectAtIndex:indexPath.section];
            }else{
                BOOL isSelect = YES;
                [self.shopCartDic setObject:array forKey:self.shopNameArray[indexPath.section]];
                //看该商店的所有商品是否都在已选里面
                for (ShopCartModel *temp in array) {
                    if (![self.selectedArray containsObject:temp]) {
                        isSelect = NO;
                    }
                }
                //添加商店
                if (isSelect) {
                    if (![self.selectedStoreArr containsObject:@(model.cart_id)]) {
                        [self.selectedStoreArr addObject:@(model.cart_id)];
                    }
                }
            }
            [self.modelArr removeObject:model];
            //看是否全选中
            //            NSEnumerator *e1 = [self.modelArr objectEnumerator];
            //            NSEnumerator *e2 = [self.selectedArray objectEnumerator];
            NSSet *s1 = [[NSSet alloc]initWithArray:self.modelArr];
            NSSet *s2 = [[NSSet alloc] initWithArray:self.selectedArray];
            if ([s1 isEqual:s2]) {
                self.bottonView.selectedBtn.selected = YES;
            }
            if (self.modelArr.count == 0) {
                //结算隐藏 编辑隐藏 显示无网络
                self.bottonView.hidden = YES;
                self.barBtn.enabled = NO;
                self.tableView.height = FTY_SCREEN_HEIGHT;
            }
            [tableView reloadData];
        }];
        return @[deleteRowAction];
    }else{
        return nil;
    }*/
    
    //设置删除按钮
    if (_modelArr.count > 0) {
        
        UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
            
            
            //1 删除操作 给后台发送删除请求
            //2 删除 缓存数据
            //3 合计金额变化
            
            //2.0删除对应商品
            ShopCartModel *model = _modelArr[indexPath.row];
            [_modelArr removeObjectAtIndex:(indexPath.row)];
            //2.1删除已选中商品
            if ([self.selectedArray containsObject:model]) {
                [self.selectedArray removeObject:model];
            }
            //合计金额变化
            [self shopCartGoodViewCellChange:nil];
            NSString *cartId = [NSString stringWithFormat:@"%li",(long)model.cart_id];
            [self deleteCartGoodsByIds:cartId];
            [tableView reloadData];
        }];
        return @[deleteRowAction];
    }else{
        return nil;
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    if (indexPath.row != 0) {
        return YES;
    }else{
        return NO;
    }*/
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

#pragma mark - ShopCartGoodViewCellDelegate
- (void)shopCartGoodViewCellChange:(ShopCartGoodViewCell *)cell{
    _allSum = 0;
    for (ShopCartModel *model in self.selectedArray) {
        self.allSum += model.goods_price * model.goods_num;
    }
    _bottonView.attAllStr = [NSString stringWithFormat:@"%.2f", self.allSum];
    
    //[self updateShopCart:cell.model];
}

- (void)shopCartGoodViewCell:(ShopCartGoodViewCell *)cell withSelectedModel:(ShopCartModel *)model{
    
    if ([self.selectedArray containsObject:model]) {
        [self.selectedArray removeObject:model];
        //每当删除商品
        self.bottonView.selectedBtn.selected = NO;
        model.isSelect = NO;
        self.allSum -= model.goods_price * model.goods_num;
        
    }else{
        [self.selectedArray addObject:model];
        model.isSelect = YES;
        self.allSum += model.goods_price * model.goods_num;
        
        
    }
    BOOL isExist = YES;
    //被选中的商品商店
    NSArray *array = [self.shopCartDic objectForKey:@(model.cart_id)];
    for (ShopCartModel *model in array) {
        if (![self.selectedArray containsObject:model]) {
            isExist = NO;
            break;
        }
    }
    NSNumber *num = @(model.cart_id);
    if (isExist && (![self.selectedStoreArr containsObject:num])) {
        [self.selectedStoreArr addObject:@(model.cart_id)];
    }
    if (!isExist && ([self.selectedStoreArr containsObject:num])) {
        [self.selectedStoreArr removeObject:@(model.cart_id)];
    }
    if (self.selectedStoreArr.count == self.shopNameArray.count) {
        //全部店铺添加
        self.bottonView.selectedBtn.selected = YES;
    }
    self.bottonView.attAllStr = [NSString stringWithFormat:@"%.2f", self.allSum];
    //TODO: 该句代码影响右下角结算变化
//    self.bottonView.payStr = [NSString stringWithFormat:@"%lu", self.selectedArray.count];
    [self.tableView reloadData];
    
    
}

#pragma mark - <bottomPriceViewDelegate>

- (void)bottomPriceView:(bottomPriceView *)bottonView{
    
    if (bottonView.selectedBtn.selected) {
        
        [self.selectedArray removeAllObjects];
        [self.selectedArray addObjectsFromArray:self.modelArr];
        for (ShopCartModel *model in self.modelArr) {
            model.isSelect = YES;
        }
        [self.selectedStoreArr removeAllObjects];
        [self.selectedStoreArr addObjectsFromArray:self.shopNameArray];
        self.allSum = 0.0;
        //计算总价格
        for (ShopCartModel *model in self.selectedArray) {
            self.allSum += model.goods_price * model.goods_num;
        }
    }else{
        [self.selectedArray removeAllObjects];
        [self.selectedStoreArr removeAllObjects];
        for (ShopCartModel *model in self.modelArr) {
            model.isSelect = NO;
        }
        self.allSum = 0.0;
    }
    bottonView.attAllStr = [NSString stringWithFormat:@"%.2f", self.allSum];
//    bottonView.payStr = [NSString stringWithFormat:@"%lu", self.selectedArray.count];
    [self.tableView reloadData];
}

- (void)toPay{
    
    //拼接选择商品的cartID
    NSString *cartIDStr = @"";
    for (int i=0; i<self.selectedArray.count; i++) {
        
        ShopCartModel *model = self.selectedArray[i];
        
        if (0 == i) {
            cartIDStr = [@(model.cart_id) stringValue];
        } else {
            DLog(@"拼接前====%@", [@(model.cart_id) stringValue]);
            cartIDStr = [cartIDStr stringByAppendingFormat:@",%@", [@(model.cart_id) stringValue]];
            DLog(@"拼接后====%@",cartIDStr);
        }
    }
    
    NSString *editTitle = self.barBtn.title;
    if ([editTitle isEqualToString:@"编辑"]) {
        //结算
        if (self.selectedArray.count > 0) {
            RWBalanceViewController *balanceVC = [[RWBalanceViewController alloc] init];
            balanceVC.hidesBottomBarWhenPushed = YES;
            balanceVC.cartIDs = cartIDStr;
            [self.navigationController pushViewController:balanceVC animated:YES];
        } else {
            [[FTYToastView alloc] addTitle:@"您还未选择商品" addView:self.view];
        }
    } else {
      //删除
        if (self.selectedArray.count > 0) {
            
            //将选择数组从总数组内删除
            [_modelArr removeObjectsInArray:self.selectedArray];
            
            //合计金额变化
            [self shopCartGoodViewCellChange:nil];
            
            //是否全选
            NSSet *s1 = [[NSSet alloc] initWithArray:self.modelArr];
            NSSet *s2 = [[NSSet alloc] initWithArray:self.selectedArray];
            if ([s1 isEqual:s2]) {
                if (self.modelArr.count) {
                    self.bottonView.selectedBtn.selected = YES;
                }else {
                    self.bottonView.selectedBtn.selected = NO;
                }
            } else {
                self.bottonView.selectedBtn.selected = NO;
            }
            /*
            //调删除接口
            NSInteger minusNumber = _selectedArray.count;
            FTYUser *user = [FTYUser sharedUser];
            [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=delcartgoods&member_id=%@&token=%@&cart_id=%@", user.userID, user.userToken, cartIDStr] parameters:nil block:^(id result, NSError *error) {
                
                if (!error) {
                    
                    DLog(@"====%@", result);
                    FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
                    baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
                    FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
                    
                    if (0 == errorInfo.errorcode) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"MinusShopCartNumberNotification" object:@{@"number": @(minusNumber)}];
                    } else {
                        [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
                    }
                } else {
                    
                }
            }];
            */
            [self deleteCartGoodsByIds:cartIDStr];
            [self.selectedArray removeAllObjects];
            //刷新table
            [self.tableView reloadData];
            
        } else {
            [[FTYToastView alloc] addTitle:@"您还未选择商品" addView:self.view];
        }
    }
   
}

//更新购物车商品数量
- (void)updateShopCart:(ShopCartModel *)cartModel
{
    NSString *cartId = [NSString stringWithFormat:@"%ld",cartModel.cart_id];
    [FTYShoppingCartPort updateShoppingCartWithShopCartID:cartId goodsNum:cartModel.goods_num viewController:self block:nil];
}
- (void)deleteCartGoodsByIds:(NSString*)cartID
{
    //调删除接口
    //NSInteger minusNumber = _selectedArray.count;
    NSInteger minusNumber = 0;
    NSArray *arr = [cartID componentsSeparatedByString:@","];
    DLog(@"arr:%@,arrCounrt:%ld",arr,arr.count);
    if (arr) {
        minusNumber = arr.count;
    }else{
        minusNumber = 1;
    }
    
    FTYUser *user = [FTYUser sharedUser];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=delcartgoods&member_id=%@&token=%@&cart_id=%@", user.userID, user.userToken, cartID] parameters:nil block:^(id result, NSError *error) {
        
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"MinusShopCartNumberNotification" object:@{@"number": @(minusNumber)}];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            
        }
    }];
    
}


#pragma mark - <UITextFieldDelegate>

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.countText = textField;
    self.currentCount = [textField.text integerValue];
    ShopCartGoodViewCell *cell = (ShopCartGoodViewCell *)textField.superview.superview;
    self.currentModel = cell.model;
    self.currentCell = cell;
    NSLog(@"%f", CGRectGetMaxY(cell.frame));
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView animateWithDuration:0.25 animations:^{
        self.tableView.y = 0;
    }];
}

//移除
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
